package club.itstudio.IContainer.controller.student;

import club.itstudio.IContainer.annotation.LoginRequired;
import club.itstudio.IContainer.annotation.StudentRequired;
import club.itstudio.IContainer.entity.Course;
import club.itstudio.IContainer.entity.StudentCourse;
import club.itstudio.IContainer.entity.StudentCourseApplication;
import club.itstudio.IContainer.entity.User;
import club.itstudio.IContainer.exception.ParamInvalidException;
import club.itstudio.IContainer.service.AuthService;
import club.itstudio.IContainer.service.CourseService;
import club.itstudio.IContainer.service.StudentCourseApplicationService;
import club.itstudio.IContainer.service.StudentCourseService;
import club.itstudio.IContainer.util.Result;
import club.itstudio.IContainer.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/student/course")
public class StudentCourseController {

    private AuthService authService;
    private CourseService courseService;
    private StudentCourseService studentCourseService;
    private StudentCourseApplicationService studentCourseApplicationService;
    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Autowired
    public void setAuthService(AuthService authService) {
        this.authService = authService;
    }

    @Autowired
    public void setCourseService(CourseService courseService) {
        this.courseService = courseService;
    }

    @Autowired
    public void setStudentCourseService(StudentCourseService studentCourseService) {
        this.studentCourseService = studentCourseService;
    }

    @Autowired
    public void setStudentCourseApplicationService(StudentCourseApplicationService studentCourseApplicationService) {
        this.studentCourseApplicationService = studentCourseApplicationService;
    }

    @LoginRequired
    @StudentRequired
    @GetMapping
    public Result getCourse(@RequestParam int page, @RequestParam int limit) {

        User student = authService.threadLocalUsers.get();
        String sql = "SELECT\n" +
                "\tstudent_course_list.*,\n" +
                "\t`user`.username \n" +
                "FROM\n" +
                "\t(\n" +
                "\tSELECT\n" +
                "\t\tstudent_course.id,\n" +
                "\t\tstudent_course.user_id,\n" +
                "\t\tstudent_course.course_id,\n" +
                "\t\tcourse.course_name,\n" +
                "\t\tcourse.description,\n" +
                "\t\tcourse.created_time,\n" +
                "\t\tcourse.teacher_id \n" +
                "\tFROM\n" +
                "\t\tstudent_course\n" +
                "\t\tJOIN course ON student_course.course_id = course.id \n" +
                "\tWHERE\n" +
                "\t\tstudent_course.user_id = ? \n" +
                "\t) AS student_course_list\n" +
                "\tJOIN `user` ON student_course_list.teacher_id = `user`.id \n" +
                "ORDER BY\n" +
                "\tid DESC \n" +
                "\tLIMIT ?,?";
         List<HashMap<String, Object>> data = jdbcTemplate.query(sql, (RowMapper) (resultSet, i) -> {
             HashMap<String, Object> map = new HashMap<>();
             map.put("id", resultSet.getInt("id"));
             map.put("user_id", resultSet.getInt("user_id"));
             map.put("course_id", resultSet.getInt("course_id"));
             map.put("courseName", resultSet.getString("course_name"));
             map.put("description", resultSet.getString("description"));
             map.put("createdTime", resultSet.getLong("created_time"));
             map.put("teacher_id", resultSet.getInt("teacher_id"));
             map.put("teacher_name", resultSet.getString("username"));
             return map;
         }, student.id, (page - 1) * limit, limit);

         int count = jdbcTemplate.queryForObject("select count(*) from student_course where user_id=?", Integer.class, student.id);

         HashMap<String, Object> result = new HashMap<>();
         result.put("content", data);
         result.put("total", count);

        return ResultUtil.success(result);
    }

    @LoginRequired
    @StudentRequired
    @PostMapping
    public Result applyCourse(@RequestParam int courseID) {
        Course course = courseService.getCourseByID(courseID);
        if (course == null) throw new ParamInvalidException("该课程不存在，请检查课程ID是否正确");

        User student = authService.threadLocalUsers.get();
        StudentCourse studentCourse = studentCourseService.getByUserIDAndCourseID(student.id, course.id);
        if (studentCourse != null) throw new ParamInvalidException("您已在课程内，不需要重复加入");

        if (course.addType == 0) {
            StudentCourse newStudentCourse = new StudentCourse();
            newStudentCourse.userID = student.id;
            newStudentCourse.courseID = course.id;
            boolean success = studentCourseService.insert(newStudentCourse);
            if (!success) {
                return ResultUtil.error("加入失败，请稍后再试");
            }
            return ResultUtil.success("加入成功");
        }

        if (course.addType == 1) {
            StudentCourseApplication application = studentCourseApplicationService.getByUserIDAndCourseID(student.id, course.id);
            if (application != null) throw new ParamInvalidException("您已申请该课程，不要重复申请");

            StudentCourseApplication newApplication = new StudentCourseApplication();
            newApplication.userID = student.id;
            newApplication.courseID = course.id;
            newApplication.status = 0;

            boolean success = studentCourseApplicationService.insert(newApplication);
            if (!success) {
                return ResultUtil.error("申请失败，请稍后再试");
            }
            return ResultUtil.success("申请成功，请等待审核结果");
        }

        return ResultUtil.error("加入失败");
    }
}
